<template>
  <div class="mubao_create">
    <div class="top_treadcrumb">
      <span class="lander_detail_back" title="返回"
        ><svg class="icon" aria-hidden="true" @click="back">
          <use xlink:href="#icon-fanhuihong1"></use></svg
      ></span>
      母包<span v-if="this.actionType === 'create'">创建</span>
      <span v-else-if="this.actionType === 'edit'">编辑</span>
      <span v-else>查看</span>
    </div>
    <div class="mubao_content">
      <el-form
        :model="form"
        :rules="rules"
        ref="form"
        label-width="112px"
        v-loading="loading"
        element-loading-text="文件上传中"
      >
        <el-form-item
          :class="actionType === 'detail' ? 'detail_item' : ''"
          label="母包标识名称"
          prop="packagename"
        >
          <span v-if="actionType === 'detail'">{{ form.packagename }}</span>
          <el-input
            v-else
            placeholder="请填写母包标识名称"
            style="width: 240px;"
            v-model="form.packagename"
          ></el-input>
        </el-form-item>
        <el-form-item
          :class="actionType === 'detail' ? 'detail_item' : ''"
          label="游戏分组"
          prop="gamegroupid"
        >
          <span v-if="actionType === 'detail'">{{
            form.gamegroupname || "-"
          }}</span>
          <el-select
            v-else
            style="width: 240px;"
            filterable
            v-model="form.gamegroupid"
            placeholder="请选择"
            @change="gameGroupChange()"
            :disabled="actionType === 'edit'"
          >
            <el-option
              v-for="item in groupsOption"
              :key="item.id"
              :label="
                item.groupname +
                  ' (' +
                  item.id +
                  ') - ' +
                  clientTypeName(item.grouptype)
              "
              :value="item.id"
            >
              <span style="float: left">{{
                item.groupname +
                  " (" +
                  item.id +
                  ") - " +
                  clientTypeName(item.grouptype)
              }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          :class="actionType === 'detail' ? 'detail_item' : ''"
          label="类型"
          prop="clientType"
          style="margin-bottom:10px;"
        >
          <span v-if="actionType === 'detail'">
            <span v-if="form.clientType === 0">端游</span>
            <span v-else-if="form.clientType === 1">Android</span>
            <span v-else>IOS</span>
          </span>
          <div v-else>
            <span v-if="form.clientType === 0 && form.gamegroupid">端游</span>
            <div v-if="form.clientType !== 0 && form.gamegroupid">
              <span>手游</span>
              <el-checkbox-group
                v-model="createCheckbox"
                v-if="actionType === 'create'"
              >
                <el-checkbox :label="1">Android</el-checkbox>
                <el-checkbox :label="2">IOS</el-checkbox>
              </el-checkbox-group>
              <el-radio-group v-model="form.clientType" v-else>
                <el-radio :label="1" :disabled="actionType === 'edit'"
                  >Android</el-radio
                >
                <el-radio :label="2" :disabled="actionType === 'edit'"
                  >IOS</el-radio
                >
              </el-radio-group>
            </div>
          </div>
        </el-form-item>
        <el-form-item
          v-if="form.clientType === 2 || createCheckbox.indexOf(2) !== -1"
          :class="actionType === 'detail' ? 'detail_item' : ''"
          label="游戏包上传"
          prop="officialUrl"
        >
          <div v-if="actionType === 'create'">
            <el-radio-group v-model="uploadType">
              <el-radio :label="1">本地上传</el-radio>
              <el-radio :label="2">地址上传</el-radio>
            </el-radio-group>
            <el-upload
              v-show="uploadType === 1"
              class="upload-demo"
              :headers="token"
              drag
              :data="fileData"
              :limit="1"
              :action="baseUrl + 'v2/ParentPackage/upload'"
              :before-upload="beforeAvatarUpload"
              :on-error="handleError"
              :on-success="handleSuccess"
              accept=".ipa"
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">
                <p>点击或将文件拖拽到这里上传</p>
                <p class="upload__text_note">仅支持上传ipa文件，且不超过50mb</p>
              </div>
            </el-upload>
            <div v-show="uploadType === 2">
              <el-input
                style="width:832px;"
                placeholder="请输入以http或https开头，以文件后缀名为结尾的地址"
                v-model="form.officialUrl"
              ></el-input>
            </div>
          </div>
          <span v-if="actionType !== 'create' && uploadType === 1"
            >游戏包地址：{{ form.officialUrl }}</span
          >
        </el-form-item>
        <el-form-item
          :class="actionType === 'detail' ? 'detail_item' : ''"
          label="是否通用"
          prop="commontype"
        >
          <span v-if="actionType === 'detail'">{{
            form.commontype ? "是" : "否"
          }}</span>
          <el-radio-group v-else v-model="form.commontype">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          :class="actionType === 'detail' ? 'detail_item' : ''"
          label="推广商"
          prop="packageagencyArr"
          v-if="!form.commontype"
        >
          <span v-if="actionType === 'detail'">{{ packageagencyName || "-" }}</span>
          <el-select
            v-else
            multiple
            filterable
            style="width: 240px;"
            v-model="form.packageagencyArr"
            placeholder="请选择"
          >
            <el-option
              v-for="item in assistantOption"
              :key="item.id"
              :label="item.username + ' ( ' + item.id + ' )'"
              :value="item.id"
            >
              <span style="float: left"
                >{{ item.username }} ( {{ item.id }} )</span
              >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="actionType !== 'detail'"
          :class="actionType === 'detail' ? 'detail_item' : ''"
          label="同步推广商"
        >
          <el-input
            placeholder="请输入推广商ID并用“,”隔开"
            style="width: 240px;"
            v-model="agencyByPro"
            @input="handInput(agencyByPro)"
          ></el-input>
          <el-button
            class="agencyByPro_btn"
            style="width: 87px;"
            type="primary"
            @click="addAgencyBtn()"
            :disabled="!agencyByPro"
            >识别添加</el-button
          >
          <span
            v-show="agencyByProError"
            style="font-size:12px;line-height:36px;margin-left:12px"
          >
            <span style="color:#e02020;">同步失败ID：</span
            ><span>{{ agencyByProErrorText }}</span>
          </span>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <span v-if="actionType === 'detail'">{{ form.remark || "-" }}</span>
          <el-input
            v-else
            style="width:832px;"
            type="textarea"
            placeholder="请输入"
            maxlength="150"
            v-model="form.remark"
            show-word-limit
          ></el-input>
        </el-form-item>
        <div style="text-align: center;padding-bottom: 28px;margin-top:60px;">
          <el-button style="width: 87px;" @click="cancel('form')">
            取消
          </el-button>
          <el-button
            v-if="actionType === 'create' && createCheckbox.length <= 1"
            style="width: 87px;"
            type="primary"
            @click="createProgram('form')"
            >创建</el-button
          >
          <el-button
            v-else-if="actionType === 'create' && createCheckbox.length === 2"
            style="width: 87px;"
            type="primary"
            @click="createCheckboxProgram('form')"
            >创建</el-button
          >
          <el-button
            v-else-if="actionType === 'edit'"
            style="width: 87px;"
            type="primary"
            @click="editProgram('form')"
            >确认</el-button
          >
          <!-- <el-button
            v-else
            style="width: 87px;"
            type="primary"
            @click="editItem('form')"
            >编辑</el-button
          > -->
        </div>
      </el-form>
    </div>
    <change-log v-if="actionType === 'detail'" :id="mbid"></change-log>
  </div>
</template>

<script>
import {
  getGameGroupList,
  getParentPackageById,
  addParentPackage,
  addMobileAPackage,
  modifyPackage
} from "@/api/mubao";
import changeLog from "./changelog";
import { addAgencyByPro } from "@/api/data";
import { getList } from "@/api/data";
import { URL_ENV } from "@/utils/request";
import { getToken } from "@/utils/auth";

export default {
  components: { changeLog },
  data() {
    var validOfficialUrl = (rule, value, callback) => {
      if (this.loading) {
        callback(new Error("文件上传中"));
      }
      if (value === "") {
        callback(new Error("请输入文件地址或上传文件"));
      } else {
        if (
          value.substring(0, 5) === "https" ||
          value.substring(0, 4) === "http"
        ) {
          callback();
        } else {
          callback(new Error("文件地址格式不正确"));
        }
      }
    };
    return {
      loading: false,
      baseUrl: URL_ENV[process.env.VUE_APP_CURRENTMODE],
      actionType: "detail",
      token: {
        Authorization: "Bearer " + getToken()
      },
      fileData: {
        name: ""
      },
      mbid:'',
      agencyByPro: "",
      agencyByProError: false,
      agencyByProErrorText: "",
      groupsOption: [],
      assistantOption: [],
      uploadType: 1,
      createCheckbox: [],
      form: {
        packagename: "", //母包标识名称
        agentid: "", //代理商ID
        packageagencyArr: [], // 母包关联推广商
        packageagency: [],
        commontype: "", //是否通用
        gamegroupid: "", //游戏分组id
        officialUrl: "", // ios母包文件地址
        gamegroupname: "", //游戏分组名称
        clientType: "", //登录器类型
        remark: ""
      },
      packageagencyNameArr:[],
      rules: {
        packagename: [
          { required: true, message: "请填写母包标识名称", trigger: "change" }
        ],
        gamegroupid: [
          { required: true, message: "请选择游戏分组", trigger: "change" }
        ],
        commontype: [
          { required: true, message: "请选择是否通用", trigger: "change" }
        ],
        packageagencyArr: [
          { required: true, message: "请选择推广商", trigger: "change" }
        ],
        officialUrl: [{ validator: validOfficialUrl, trigger: "change" }]
      }
    };
  },
  created() {
    this.getGameGroupList();
    this.getList();
    this.actionType = this.$route.query.type;
    if (this.$route.query.id) {
      this.mbid = this.$route.query.id;
      this.getDetailInfo();
    }
  },
  computed: {
    packageagencyName() {
      let str = '';
      this.packageagencyNameArr.forEach((item,index)=>{
        str += item+"("+this.form.packageagencyArr[index]+")，"
      })
      str = str.substring(0,str.length-1);
      return str;
    },
    clientTypeName() {
      return function(type) {
        let typename = "";
        switch (type) {
          case 0:
            typename = "端游";
            break;
          case 1:
            typename = "手游";
            break;
          case 2:
            typename = "IOS";
            break;
        }
        return typename;
      };
    }
  },
  methods: {
    cancel() {
      this.$router.back();
    },
    // input输入框输入限制
    handInput(data) {
      // this.$set(this.agencyByPro,'value',data.replace(/[^0-9]/g,''));
      this.agencyByPro = data.replace(/[^0-9,]/g, "");
    },
    // 获取详情
    getDetailInfo() {
      getParentPackageById({ id: this.$route.query.id }).then(res => {
        this.form.packageagencyArr = [];
        res.data.packageagencydto.filter(item => {
          this.form.packageagencyArr.push(item.assistantagencyid);
          this.packageagencyNameArr.push(item.assistantagencyname);
        });
        this.form.packagename = res.data.packagename;
        this.form.gamegroupid = res.data.gamegroupid;
        this.form.gamegroupname = res.data.gamegroupname;
        this.form.clientType = res.data.clienttype;
        this.form.commontype = res.data.commontype;
        this.form.agentid = res.data.assistantagencyid;
        this.form.remark = res.data.remark;
        this.form.officialUrl = res.data.officialurl;
      });
    },
    // 创建母包
    createProgram() {
      if (this.loading) {
        this.$message.error("母包正在上传，请稍后再试。");
        return;
      }
      this.$refs.form.validate(valid => {
        if (valid) {
          console.log(this.createCheckbox)
          if(this.createCheckbox.length < 1){
            return this.$message.error('请选择母包类型');
          }else{
            this.form.clientType = this.createCheckbox[0];
          }
          this.form.packageagency = [];
          this.form.packageagencyArr.forEach((element, index) => {
            var row = this.assistantOption.filter(item => {
              if (item.id === element) {
                return item;
              }
            })[0];
            this.form.packageagency[index] = {
              id: 0,
              createdat: row.createdat,
              updatedat: row.updatedat,
              packageid: 0,
              assistantagencyid: row.id
            };
          });
          addParentPackage(this.form).then(res => {
            if (res.code === 0) {
              this.$message({
                message: "添加成功",
                type: "success"
              });
              this.$router.back();
            } else {
              this.$message.error(res.message);
            }
          });
        }
      });
    },
    // 创建多个母包
    createCheckboxProgram() {
      if (this.loading) {
        this.$message.error("母包正在上传，请稍后再试。");
        return;
      }
      this.$refs.form.validate(valid => {
        if (valid) {
          let data = {
            packagename: this.form.packagename,
            agentid: 0,
            packageagency: [],
            commontype: this.form.commontype,
            gamegroupid: this.form.gamegroupid,
            clientType: 1, // 创建多个默认选1
            ipaName: "",
            officialUrl: this.form.officialUrl,
            remark: this.form.remark
          };
          this.form.packageagencyArr.forEach((element, index) => {
            var row = this.assistantOption.filter(item => {
              if (item.id === element) {
                return item;
              }
            })[0];
            data.packageagency[index] = {
              id: 0,
              createdat: row.createdat,
              updatedat: row.updatedat,
              packageid: 0,
              assistantagencyid: row.id
            };
          });
          addMobileAPackage(data).then(res => {
            if (res.code === 0) {
              this.$message({
                message: "添加成功",
                type: "success"
              });
              this.$router.back();
            } else {
              this.$message.error(res.message);
            }
          });
        }
      });
    },
    // 编辑母包
    editProgram() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.form.packageagency = [];
          this.form.packageagencyArr.forEach((element, index) => {
            var row = this.assistantOption.filter(item => {
              if (item.id === element) {
                return item;
              }
            })[0];
            this.form.packageagency[index] = {
              id: 0,
              createdat: row.createdat,
              updatedat: row.updatedat,
              packageid: 0,
              assistantagencyid: row.id
            };
          });
          this.form.id = this.$route.query.id;
          modifyPackage(this.form).then(res => {
            if (res.code === 0) {
              this.$message({
                message: "修改成功",
                type: "success"
              });
              this.$router.back();
            } else {
              this.$message.error(res.message);
            }
          });
        }
      });
    },
    // 去编辑母包
    editItem() {
      this.actionType = "edit";
    },
    // 同步推广商
    addAgencyBtn() {
      var that = this;
      var dataArr = this.agencyByPro.split(",");
      for (var i = 0; i < dataArr.length; i++) {
        if (dataArr[i] == "" || typeof dataArr[i] == "undefined") {
          dataArr.splice(i, 1);
          i = i - 1;
        }
      }
      this.agencyByPro = dataArr.join(",");
      addAgencyByPro({
        id: this.$route.query.id,
        idList: dataArr
      }).then(res => {
        if (res.code === 0) {
          this.$message({
            message: "推广商识别完成",
            type: "success"
          });
          that.getList();
          res.data.successids.split(",").forEach(item => {
            if (item) {
              that.form.packageagencyArr.push(+item);
            }
          });
          that.agencyByProErrorText = res.data.errorids;
          that.agencyByProError = true;
        } else {
          this.$message.error(res.message);
        }
      });
    },
    beforeAvatarUpload(file) {
      this.loading = true;
      const isIPA = file.name.substring(file.name.length - 4) === ".ipa";
      const isLt50M = file.size / 1024 / 1024 < 50;
      if (!isIPA) {
        this.$message.error("上传文件只能是 ipa 格式!");
      }
      if (!isLt50M) {
        this.$message.error("上传文件大小不能超过 50MB!");
      }
      this.fileData.name = file.name;
      let formField = this.$refs["form"].fields;
      formField.map(i => {
        if (i.prop === "officialUrl") {
          //通过prop属性值相同来判断是哪个输入框，比如：要移除prop为'imageUrl'
          i.clearValidate();
          return false;
        }
      });
      return isIPA && isLt50M;
    },
    handleSuccess(res) {
      this.loading = false;
      if (res.code === 0) {
        this.$message({ message: "上传成功", type: "success" });
        this.form.officialUrl = res.data;
      } else {
        this.$message.error(res.message);
      }
    },
    handleError(err) {
      this.$message.error("上传失败");
      this.loading = false;
      console.log(err);
    },
    getGameGroupList() {
      getGameGroupList().then(res => {
        this.groupsOption = res.data;
      });
    },
    getList() {
      getList().then(res => {
        this.assistantOption = res.data;
      });
    },
    clientTypeChange() {},
    gameGroupChange() {
      let row = this.groupsOption.filter(item => {
        if (item.id === this.form.gamegroupid) {
          return item;
        }
      });
      this.form.gamegroupname = row[0].groupname;
      this.form.clientType = row[0].grouptype;
      this.createCheckbox = [row[0].grouptype];
      this.form.officialUrl = "";
    },
    // 返回
    back() {
      this.$router.back();
    }
  }
};
</script>

<style lang="scss" scoped>
.mubao_create {
  .agencyByPro_btn {
    &:hover {
      background: #ef6767;
      border-color: #ef6767;
    }
    margin-left: 8px;
    border-color: #eb3737;
    background: #eb3737;
  }
  .el-button--primary.is-disabled {
    &:hover,
    &:focus,
    &:active {
      border-color: #979797;
      background: #979797;
    }
    border-color: #979797;
    background: #979797;
  }
  .lander_detail_back .icon {
    width: 24px;
    height: 24px;
    vertical-align: top;
    margin-right: 10px;
    cursor: pointer;
  }
  .top_treadcrumb {
    font-family: PingFangSC-Semibold;
    font-size: 18px;
    color: #141414;
    letter-spacing: 0;
    line-height: 24px;
    font-weight: 600;
  }
  .mubao_content {
    background: #ffffff;
    box-shadow: 0 0 6px 0 rgba(0, 21, 41, 0.09);
    border-radius: 4px;
    padding: 28px 32px 0 32px;
    margin: 0 0 16px 0;
    margin-top: 21px;
  }
  .small_btn {
    width: 14px;
    height: 14px;
    color: #fff;
    box-sizing: border-box;
    line-height: 14px;
    display: inline-block;
    text-align: center;
    border-radius: 50%;
    cursor: pointer;
  }
  .add_btn {
    background: var(--themeColor);
    margin: 0 16px;
  }
  .reduce_btn {
    background: var(--themeColor);
  }
  .care_item {
    margin-bottom: 20px;
  }
  .tips {
    p {
      line-height: 18px;
      span {
        color: #e02020;
      }
    }
  }
  .detail_item {
    margin-bottom: 0px;
  }
  .el-upload__text {
    line-height: 20px;
  }
  .upload__text_note {
    color: #777;
    font-size: 12px;
  }

  .upload-demo {
    width: 400px;
  }
}
</style>
<style>
/* .upload-demo .loading_st{
      bottom:40px;
    } */
</style>
